<template>
    <el-dialog v-model="dialogFormVisible" title="手机绑定" width="500" :show-close="true" :close-on-click-modal="false"
        :close-on-press-escape="false" class="dialog">
        <el-form :model="form" ref="formRef" label-width="100px" v-loading="formLoading" :rules="formRules">
            <el-form-item prop="phone">
                <el-input v-model="form.phone" placeholder="请输入手机号"/>
            </el-form-item>
            <el-form-item prop="code">
                <el-input v-model="form.code" placeholder="请输入验证码" />
                <span class="link-btn">
                    <el-divider direction="vertical" />
                    <el-button link @click="sendVerificationCode" :disabled="isCounting" type="primary">
                        {{ counter > 0 ? `${counter} 秒后重新发送` : '获取验证码' }}
                    </el-button>
                </span>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitForm" class="confirm">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { service } from '@/config/service'
import { ref, reactive, onUnmounted, computed } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()
const allToken = computed(() => userStore.allToken)
const dialogFormVisible = ref(false)
const form = ref({})
const formRef = ref()
const formLoading = ref(false)
const formRules = reactive({
    phone: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
    code: [{ required: true, message: '验证码不能为空', trigger: 'blur' }]
})
let counter = ref(0);
let timer = null;
let isCounting = ref(false);
const emit = defineEmits(['success','exit'])

/** 打开弹窗 */
const open = async () => {
    dialogFormVisible.value = true
    resetForm()
}
const close = () => {
    dialogFormVisible.value = false
}
/** 重置表单 */
const resetForm = () => {
    form.value = {
        phone: '',
        code: ''
    }
    formRef.value?.resetFields()
}

const getCode = () => {
    let res = service.get(`https://api.geovisearth.com/passport/auth/sendSmsCode?phone=${form.value.phone}`)
    return res
}

defineExpose({ open })

const submitForm = async () => {
    // 校验表单
    if (!formRef) return
    const valid = await formRef.value.validate()
    if (!valid) return
    // 提交请求
    formLoading.value = true
    try {
        const data = form.value
        let result = await service.post('https://api.geovisearth.com/passport/account/bindPhone', { ...data }, {
            headers: {
                Authorization: `Bearer ${allToken.value.accessToken}`
            }
        })
        if (result.Success) {
            ElMessage({
                message: '绑定成功',
                type: 'success',
            })
            emit('success')
            dialogFormVisible.value = false
        } else if (result.Message == '手机号已经被使用') {
            ElMessage({
                message: result.Message + ',请使用手机号登录！',
                type: 'warning',
            })
            emit('exit')
            dialogFormVisible.value = false
        } else {
            ElMessage({
                message: result.Message,
                type: 'warning',
            })
        }
    } finally {
        formLoading.value = false
    }
}

const sendVerificationCode = () => {
    if (isCounting.value) return;
    if (!form.value.phone) {
        ElMessage({
            message: '请输入手机号/邮箱',
            type: 'warning',
        })
        return
    }
    getCode();
    isCounting.value = true;
    counter.value = 60;
    // 倒计时60秒
    timer = setInterval(() => {
        counter.value--;
        if (counter.value <= 0) {
            clearInterval(timer);
            isCounting.value = false;
            counter.value = 0;
        }
    }, 1000);
};
// 组件卸载时清除定时器 
onUnmounted(() => {
    if (timer) {
        clearInterval(timer);
    }
});

</script>

<style lang="scss">
.link-btn {
    position: absolute;
    right: 10px;
    line-height: 22px !important;
    cursor: pointer;

    .el-button {
        color: #0084cb !important;
        font-size: 16px !important;
    }
}

.dialog {
    position: relative !important;
    box-sizing: border-box !important;
    width: 438px !important;
    height: 400px;
    border-radius: 16px !important;
    padding: 32px 43px 0 !important;
    display: flex;
    flex-direction: column;
    align-items: center;

    .el-dialog__header {
        color: #212121;
        padding-bottom: 6px;
        border-bottom: 2px solid #0084cb;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 700;
        margin-bottom: 50px;
        display: flex;
        justify-content: center;
        padding-right: 0 !important;

        span {
            font-size: 20px;
        }
    }

    .el-dialog__body {
        width: 100%;
    }

    .el-dialog__headerbtn {
        font-size: 25px;
        font-weight: bold;
    }

    .el-form-item__content {
        margin-left: 0 !important;
    }

    .el-input__wrapper {
        box-sizing: border-box;
        width: 100%;
        height: 48px;
        font-size: 16px;
        border-radius: 8px;
        padding: 12px 12px 12px 20px;
        outline: none;
        background-color: #fff;
        color: rgba(0, 0, 0, .87);
        caret-color: #0084cb;
    }

    .el-dialog__footer {
        width: 100%;
    }

    .confirm {
        box-sizing: border-box;
        width: 100% !important;
        padding: 14px !important;
        line-height: 50px !important;
        height: 50px;
        display: flex;
        justify-content: center;
        align-items: center;
        background: linear-gradient(90deg, #0085cc, #00448c);
        box-shadow: 0 2px 21px 0 rgba(10, 126, 255, .25) !important;
        border-radius: 8px !important;
        font-size: 16px !important;
        margin-bottom: 0;
        cursor: pointer;
    }
}
</style>